package com.example.project.config;

import com.example.project.exception.AuthException;
import com.example.project.vo.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
@ResponseBody//此注解用于输出json格式异常结果
public class GlobalExceptionHandler {

    //鉴权登入异常
    @ResponseBody//此注解用于输出json格式异常结果
    @ExceptionHandler(AuthException.class)
    public Result AuthException(AuthException e) {
        String name = e.getClass().getName();
        name = name.substring(name.lastIndexOf(".")+1);
        log.error("{},code:{},message:{}",name,e.getCode(),e.getMessage());
        return Result.fail(e.getCode(),e.getMessage());
    }

    // 参数校验的异常处理
    @ResponseBody//此注解用于输出json格式异常结果
    @ExceptionHandler(BindException.class)
    public Result validatedBindException(BindException e) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        log.error("BindException异常:{}",e.getMessage());
        return Result.fail(message);
    }

    // 控制器层的全局异常处理
    // ExceptionHandler 注解的作用是：要处理哪种类信息的异常

    @ResponseBody//此注解用于输出json格式异常结果
    @ExceptionHandler(RuntimeException.class)
    public Result handlerException(RuntimeException e) {
        log.error("RuntimeException异常:{}",e.getMessage());
        return Result.fail(e.getMessage());
    }

    @ResponseBody//此注解用于输出json格式异常结果
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {
        log.error("Exception异常:{}",e.getMessage());
        return Result.fail(e.getMessage());
    }
}
